package middleware

import (
	"net/http"
	"strings"
)

var xForwardedFor = http.CanonicalHeaderKey("X-Forwarded-For")
var xRealIP = http.CanonicalHeaderKey("X-Real-IP")

func RealIp(context Context, next Next) error {
	var ip string
	if xff := context.Header(xForwardedFor); xff != "" {
		i := strings.Index(xff, ", ")
		if i == -1 {
			i = len(xff)
		}
		ip = xff[:i]
	} else if xrip := context.Header(xRealIP); xrip != "" {
		ip = xrip
	}
	if ip != "" {
		req := context.Request()
		req.RemoteAddr = ip
	}
	return next(nil)
}
